import React, { useState, useEffect, Suspense, lazy } from 'react';
import { createBrowserRouter, createRoutesFromElements, Route, Navigate, useLocation } from 'react-router-dom';
import useAuthStore from '../stores/authStore';
import { Spin } from 'antd';

// 导入布局组件
import MainLayout from '../layouts/MainLayout';

// 懒加载页面组件
const Login = lazy(() => import('../pages/Login'));
const Dashboard = lazy(() => import('../pages/Dashboard'));
const Carousel = lazy(() => import('../pages/Carousel'));
const Courses = lazy(() => import('../pages/Courses'));
const Appointments = lazy(() => import('../pages/Appointments'));
const Evaluations = lazy(() => import('../pages/Evaluations'));
const Analytics = lazy(() => import('../pages/Analytics'));
const Profile = lazy(() => import('../pages/Profile'));
const Orders = lazy(() => import('../pages/Orders'));
const NotFound = lazy(() => import('../pages/NotFound'));

// 加载状态组件
const LoadingComponent = () => (
  <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
    <Spin size="large" tip="加载中..." />
  </div>
);

// 路由守卫组件
const PrivateRoute = ({ children }) => {
  const [loading, setLoading] = useState(true);
  const { isAuthenticated, user, fetchUserInfo } = useAuthStore();
  const location = useLocation();
  
  useEffect(() => {
    const init = async () => {
      try {
        // 如果已经有 token 但没有用户信息，获取用户信息
        if (isAuthenticated && !user?.id) {
          await fetchUserInfo();
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
      } finally {
        setLoading(false);
      }
    };

    init();
  }, [isAuthenticated, user?.id]);

  // 如果正在加载，显示加载状态
  if (loading) {
    return <LoadingComponent />;
  }
  
  // 如果没有认证信息，重定向到登录页
  if (!isAuthenticated) {
    return <Navigate to="/login" state={{ from: location }} replace />;
  }
  
  return children;
};

// 创建路由配置
const router = createBrowserRouter(
  createRoutesFromElements(
    <>
      <Route path="/login" element={
        <Suspense fallback={<LoadingComponent />}>
          <Login />
        </Suspense>
      } />
      <Route
        path="/"
        element={
          <PrivateRoute>
            <MainLayout />
          </PrivateRoute>
        }
      >
        <Route index element={<Navigate to="/dashboard" replace />} />
        <Route path="dashboard" element={
          <Suspense fallback={<LoadingComponent />}>
            <Dashboard />
          </Suspense>
        } />
        <Route path="carousel" element={
          <Suspense fallback={<LoadingComponent />}>
            <Carousel />
          </Suspense>
        } />
        <Route path="courses" element={
          <Suspense fallback={<LoadingComponent />}>
            <Courses />
          </Suspense>
        } />
        <Route path="appointments" element={
          <Suspense fallback={<LoadingComponent />}>
            <Appointments />
          </Suspense>
        } />
        <Route path="orders" element={
          <Suspense fallback={<LoadingComponent />}>
            <Orders />
          </Suspense>
        } />
        <Route path="evaluations" element={
          <Suspense fallback={<LoadingComponent />}>
            <Evaluations />
          </Suspense>
        } />
        <Route path="analytics" element={
          <Suspense fallback={<LoadingComponent />}>
            <Analytics />
          </Suspense>
        } />
        <Route path="profile" element={
          <Suspense fallback={<LoadingComponent />}>
            <Profile />
          </Suspense>
        } />
        <Route path="*" element={
          <Suspense fallback={<LoadingComponent />}>
            <NotFound />
          </Suspense>
        } />
      </Route>
    </>
  )
);

export default router; 